package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-08-25
 * Time: 10:32
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.从请求中获取用户名和密码
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.equals("") || password == null || password.equals("")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("<h3>缺少用户名或密码！<h3>");
            return;
        }
        // 2.读取数据库，检查用户名或密码是否存在
        UserDao userDao = new UserDao();
        User user = userDao.selectUserByName(username);
        if (user == null) {
            // 用户不存在
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("<h3>用户名或密码错误！<h3>");
            return;
        }
        if (!user.getPassword().equals(password)) {
            // 密码错误
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("<h3>用户名或密码错误！<h3>");
            return;
        }
        // 3.用户登录成功，设置会话
        HttpSession session = req.getSession(true);
        // 把用户对象存储到 session 中了. 下次用户访问其他页面, 就可以直接拿到会话, 进一步拿到之前的 user 对象
        session.setAttribute("user",user);
        // 4. 返回一个重定向响应, 跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 会话不存在（未登录）
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 会话存在但是用户对象不存在（未登录）
            resp.setStatus(403);
            return;
        }
        // 已登录状态
        resp.setStatus(200);
        // 密码置空，防止泄漏
        user.setPassword("");
        String respString = objectMapper.writeValueAsString(user);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respString);

    }
}
